﻿using BasicInformation.ApiRead.Application.Command.Inbound;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Net.NetworkInformation;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Inbound
{
    public class GetInboundHandler : IRequestHandler<GetInboundCommand, ApiPaging<InboundDTO>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetInboundHandler> logger;

        public GetInboundHandler(DatabaseContext db, ILogger<GetInboundHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }
        public async Task<ApiPaging<InboundDTO>> Handle(GetInboundCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<InboundDTO> result = new ApiPaging<InboundDTO>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();

            sql.Append(@"SELECT
	                        a.InboundId,
	                        a.InboundCode,
	                        InboundTypeName,
	                        b.DepotId,
	                        b.DepotName,
	                        a.InboundTime,
	                        a.InboundRemark 
                        FROM
	                        inboundmodel a
	                        LEFT JOIN depotmodel b ON a.DepotId = b.DepotId 
                        WHERE
	                        a.IsDel =0");
            countSql.Append(@" 	SELECT COUNT(*) FROM inboundmodel");
            sql.Append(@" 	ORDER BY a.InboundId LIMIT @size OFFSET @offset");
            var parameters = new
            {
                size = request.size,
                offset = (request.index - 1) * request.size,
            };
            try
            {
                var pageData = await db.DapperConnection.QueryAsync<InboundDTO>(sql.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                result.Msg = "亏盈显示查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (Exception)
            {

                throw;
            }
            return await Task.FromResult(result);
        }
    }
}